package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.common.ThreadLocalUtil;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.service.WmMaterialService;

import com.heima.wemedia.service.WmNewsMaterialService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.concurrent.ListenableFutureCallback;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 *  业务严谨判断的思路（可选，由业务要求来决定）
 *  1. 判断参数为空或不为空
 *  2. 判断参数值格式是否正确
 *  3. 判断参数值是否违规
 *  4. 判断数据是否存在或不存在
 *  5. 判断数据是否唯一
 *  6. 判断数据状态是否允许继续操作
 */
@Slf4j
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialService wmNewsMaterialService;

    @Autowired
    private WmMaterialService wmMaterialService;

    @Autowired
    private WmNewsAuditService wmNewsAuditService;

    @Transactional
    @Override
    public ResponseResult submit(WmNewsDto dto, Integer isSubmit) {
        //1.判断必要参数不能为空
        if(StringUtils.isBlank(dto.getTitle()) || StringUtils.isBlank(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        //2.创建或修改文章
        //2.1 复制dto给pojo
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        //2.2 单独处理images的值（将dto里的封面图片列表转为逗号拼接的地址字符串）
        if(dto.getImages()!=null && dto.getImages().size()>0){
            //String coverImageStr = String.join(",", dto.getImages());
           // String coverImageStr =  StringUtils.join(dto.getImages(), ",");
            String coverImageStr = dto.getImages().stream().collect(Collectors.joining(","));
            wmNews.setImages(coverImageStr);
        }
        //2.3 当布局方式为自动布局时，则需要将布局方式设置为临时为空（后续逻辑还会继续决定布局方式和更新布局方式）
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            wmNews.setType(null);
        }
        //2.4 根据id参数值决定创建文章还是修改文章
        ResponseResult responseResult = this.saveOrUpdateWmNews(dto, isSubmit, wmNews);
        if(responseResult!=null){
            return responseResult;
        }

        //必须是提交审核状态，才能执行后续更多逻辑
        if(isSubmit.equals(WmNews.Status.SUBMIT.getCode())){
            //3.从文章内容中抽取全部图片地址列表
            List<String> contentImageUrlList = extractContentImageUrlList(dto);

            //4.保存内容图片与文章关系
            if(contentImageUrlList.size()>0){
                responseResult = this.saveRelation(contentImageUrlList, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
                if(responseResult!=null){
                    return responseResult;
                }
            }

            //5.保存封面图片与文章关系
            responseResult = this.saveRelationForCoverImage(dto, wmNews, contentImageUrlList);
            if (responseResult!= null){
                return responseResult;
            }

            //6.触发文章自动审核（基于线程池ThreadPool技术完成自动审核）
            wmNewsAuditService.auditWmNews(wmNews, contentImageUrlList);

        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 保存封面图片与文章关系
     * @param dto
     * @param wmNews
     * @param contentImageUrlList
     * @return
     */
    private ResponseResult saveRelationForCoverImage(WmNewsDto dto, WmNews wmNews, List<String> contentImageUrlList) {
        ResponseResult responseResult;
        //1 获取dto封面图片地址列表
        List<String> coverImageUlrList =  dto.getImages();

        //2 如果是自动布局，则根据自动匹配规则决定最终封面布局方式及更新文章布局方式和封面图片
        if(dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)){
            int size = contentImageUrlList.size();

            //2.1 根据自动匹配规则决定封面图片和布局方式
            //自动匹配规则1：如果内容图片地址数量大于等于3，则取前3张图片当做封面图片，布局决定为多图布局
            if(size>=3){
                //coverImageUlrList = contentImageUrlList.subList(0,3);
                coverImageUlrList = contentImageUrlList.stream().limit(3).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);//多图布局
            } else if(size>=1 && size<3){
                //自动匹配规则2：如果内容图片地址数量大于等于1，则取前1张图片当做封面图片，布局决定为单图布局
                coverImageUlrList = contentImageUrlList.stream().limit(1).collect(Collectors.toList());
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);//单图布局
            } else {
                //自动匹配规则3：如果内容图片地址数量大于等于0，布局决定为无图布局
                coverImageUlrList = new ArrayList<>();
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);//无图布局
            }

            //2.2 如果匹配到了封面图片，则将封面图片地址转为逗号拼接的字符串
            if(coverImageUlrList.size()>0){
                String coverImageStr = coverImageUlrList.stream().collect(Collectors.joining(","));
                wmNews.setImages(coverImageStr);
            }

            //2.3 更新文章的布局方式和封面图片
            this.updateById(wmNews);
        }

        //3 保存封面图片与文章的关系到关系表
        if(coverImageUlrList!=null && coverImageUlrList.size()>0){
            responseResult = this.saveRelation(coverImageUlrList, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
            if(responseResult!=null){
                return responseResult;
            }
        }
        return null;
    }

    /**
     * 从文章内容中抽取全部图片地址列表
     * @param dto
     * @return
     */
    private static List<String> extractContentImageUrlList(WmNewsDto dto) {
        List<String> contentImageUrlList = new ArrayList<>();
        List<Map> mapList = JSON.parseArray(dto.getContent(), Map.class);
        if(mapList!=null && mapList.size()>0){
            for (Map<String,String> map : mapList) {
                String type = map.get("type");
                if("image".equals(type)){
                    String contentImageUrl = map.get("value");//内容中的图片地址
                    contentImageUrlList.add(contentImageUrl);
                }
            }
        }
        return contentImageUrlList;
    }

    private ResponseResult saveOrUpdateWmNews(WmNewsDto dto, Integer isSubmit, WmNews wmNews) {
        //补充设置更多属性的值
        wmNews.setUserId(ThreadLocalUtil.getUserId());//自媒体用户id
        wmNews.setEnable(WemediaConstants.IS_UP);//默认值：已上架
        wmNews.setStatus(isSubmit);//0-保存草稿 1-提交审核
        wmNews.setSubmitedTime(new Date());//提交时间

        //ID无值，就创建文章
        if(wmNews.getId()==null){
            wmNews.setCreatedTime(new Date());//创建时间
            this.save(wmNews);
        } else {
            //ID有值，就修改文章且删除关系

            //判断文章是否存在
            Integer count = this.lambdaQuery().eq(WmNews::getId, dto.getId()).count();
            if(count==0){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在无法修改");
            }

            //修改文章
            this.updateById(wmNews);

            //删除关系 delete from wm_news_material where news_id=?
            wmNewsMaterialService.remove(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        }
        return null;
    }

    /**
     * 公共方法：保存素材与文章的对应关系到关系表中
     * @param imageUrlList 素材列表
     * @param wmNewsId 自媒体文章id
     * @param type 引用类型0-内容引用 1-主图引用
     * @return
     */
    private ResponseResult saveRelation(List<String> imageUrlList,Integer wmNewsId,Integer type){
        //1 根据内容中的素材地址从素材表中查询素材列表 select id from wm_material where url in (?,?,?...)
        List<WmMaterial> wmMaterialList = wmMaterialService.lambdaQuery().in(WmMaterial::getUrl, imageUrlList)
                .select(WmMaterial::getId).list();

        //2 判断是否所有素材地址都查询到了素材
        if(wmMaterialList.size()!=imageUrlList.size()){
            return ResponseResult.errorResult(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
        }

        //3 获取素材列表中的所有素材ID列表
        List<Integer> materialIdList = wmMaterialList.stream().map(WmMaterial::getId).collect(Collectors.toList());

        //4 遍历素材ID列表逐一构建关系数据
        int ord = 0;
        List<WmNewsMaterial> wmNewsMaterialList = new ArrayList<>();
        for (Integer materialId : materialIdList) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setNewsId(wmNewsId); //文章id
            wmNewsMaterial.setMaterialId(materialId); //素材id
            wmNewsMaterial.setType(type);//引用类型：0-内容引用  1-主图引用
            wmNewsMaterial.setOrd(ord++);//序号

            wmNewsMaterialList.add(wmNewsMaterial);
        }

        //5 批量保存关系数据 insert into wm_news_material (news_id,material_id,type,ord) values (1,101,0,1),(1,102,0,2),(1,103,0,3)
        wmNewsMaterialService.saveBatch(wmNewsMaterialList);

        return null;
    }

    @Override
    public ResponseResult list(WmNewsPageReqDto dto) {
        //1.设置分页参数默认值
        dto.checkParam();

        //2.拼接查询条件
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        //2.1 拼接固定查询条件： 根据userId查询
        lambdaQueryWrapper.eq(WmNews::getUserId, ThreadLocalUtil.getUserId());

        //2.2 拼接动态查询条件
        //拼接根据状态查询
        lambdaQueryWrapper.eq(dto.getStatus()!=null, WmNews::getStatus, dto.getStatus());

        //拼接根据频道ID查询
        lambdaQueryWrapper.eq(dto.getChannelId()!=null, WmNews::getChannelId, dto.getChannelId());

        //拼接根据关键词模糊查询
        lambdaQueryWrapper.like(StringUtils.isNotBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword());

        //拼接根据发布时间范围查询
        lambdaQueryWrapper.between(dto.getBeginPubDate()!=null && dto.getEndPubDate()!=null,WmNews::getPublishTime, dto.getBeginPubDate(), dto.getEndPubDate());

        //2.3 设置结果排序：根据createdTime倒排序
        lambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);

        //3. 执行分页查询
        IPage<WmNews> page = new Page<>(dto.getPage(),dto.getSize());
        this.page(page,lambdaQueryWrapper);

        //4. 构建分页响应结果
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),page.getTotal());
        responseResult.setData(page.getRecords());

        return responseResult;
    }

    @Autowired
    private KafkaTemplate kafkaTemplate;


    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //1.判断文章是否存在
        WmNews wmNews = this.getById(dto.getId());
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在，无法上下架");
        }

        //2.判断文章状态是否已发布
        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "文章未发布，无法上下架");
        }

        //3.修改文章enable的值  update wm_news set enable=? where id=?
        WmNews wmNewsDB = new WmNews();
        wmNewsDB.setId(dto.getId());
        wmNewsDB.setEnable(dto.getEnable());
        this.updateById(wmNewsDB);

        //4.生产消息到kafka的主题中
        Map data = new HashMap();
        data.put("articleId", wmNews.getArticleId()); //app端文章id
        data.put("enable",dto.getEnable());//自媒体文章上下架状态
        kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC, JSON.toJSONString(data)).addCallback(new ListenableFutureCallback() {
            @Override
            public void onFailure(Throwable ex) {

            }

            @Override
            public void onSuccess(Object result) {

            }
        });

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
